import * as APP_CONFIG from '@app/app.config'
import { HttpService } from '@nestjs/axios'
import { Injectable } from '@nestjs/common'
import { getMessageFromAxiosError } from '@app/transformers/error.transformer'
import { createLogger } from '@app/utils/logger'
import { isDevEnv } from '@app/app.environment'

const logger = createLogger({ scope: 'SeoService', time: isDevEnv })

export type ActionURL = string | string[]
export enum SEOAction {
  Push = 'push',
  Update = 'update',
  Delete = 'delete',
}

@Injectable()
export class SeoService {
  constructor(private readonly httpService: HttpService) { }

  // Baidu
  private pingBaidu(action: SEOAction, urls: string[]): void {
    const urlKeyMap = {
      [SEOAction.Push]: 'urls',
      [SEOAction.Update]: 'update',
      [SEOAction.Delete]: 'del',
    }
    const urlKey = urlKeyMap[action]
    const actionText = `Baidu ping [${action}] action`

    this.httpService.axiosRef
      .request({
        method: 'post',
        data: urls.join('\n'),
        headers: { 'Content-Type': 'text/plain' },
        url: `http://data.zz.baidu.com/${urlKey}?site=${APP_CONFIG.BAIDU_INDEXED.site}&token=${APP_CONFIG.BAIDU_INDEXED.token}`,
      })
      .then((response) => {
        logger.info(`[SEO]`, `${actionText} succeed:`, urls, response.statusText)
      })
      .catch((error) => {
        logger.warn(`[SEO]`, `${actionText} failed:`, getMessageFromAxiosError(error))
      })
  }

  private humanizedUrl(url: ActionURL): string[] {
    return typeof url === 'string' ? [url] : url
  }

  public push(url: ActionURL) {
    const urls = this.humanizedUrl(url)
    this.pingBaidu(SEOAction.Push, urls)
  }

  public update(url: ActionURL) {
    const urls = this.humanizedUrl(url)
    this.pingBaidu(SEOAction.Update, urls)
  }

  public delete(url: ActionURL) {
    const urls = this.humanizedUrl(url)
    this.pingBaidu(SEOAction.Delete, urls)
  }
}
